import { FunctionOutlined } from '@ant-design/icons';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { LexicalTypeaheadMenuPlugin } from '@lexical/react/LexicalTypeaheadMenuPlugin';
import { $createTextNode, $getSelection, $isRangeSelection, TextNode } from 'lexical';
import { useCallback, useState } from 'react';
import * as ReactDOM from 'react-dom';

import { EditorVariablePickerType } from '../../type';
import { useBasicTypeaheadTriggerMatch } from '../../utils';

export default function VariablePickerPlugin({
  variables,
}: {
  variables: EditorVariablePickerType[];
}) {
  const [editor] = useLexicalComposerContext();
  const [queryString, setQueryString] = useState<string | null>(null);

  const checkForTriggerMatch = useBasicTypeaheadTriggerMatch('{', {
    minLength: 0,
  });

  const onSelectOption = useCallback(
    (selectedOption: any, nodeToRemove: TextNode | null, closeMenu: () => void) => {
      editor.update(() => {
        const selection = $getSelection();
        if (!$isRangeSelection(selection) || selectedOption == null) {
          return;
        }
        if (nodeToRemove) {
          nodeToRemove.remove();
        }
        selection.insertNodes([$createTextNode(`{{${selectedOption.key}}}`)]);
        closeMenu();
      });
    },
    [editor],
  );

  return (
    <LexicalTypeaheadMenuPlugin
      onQueryChange={setQueryString}
      onSelectOption={onSelectOption}
      triggerFn={checkForTriggerMatch}
      options={variables as any[]}
      menuRenderFn={(
        anchorElementRef,
        { selectedIndex, selectOptionAndCleanUp, setHighlightedIndex },
      ) => {
        if (anchorElementRef.current == null) {
          return null;
        }
        return anchorElementRef.current && variables.length
          ? ReactDOM.createPortal(
              <div className="border-borderColor-base z-99999 max-h-300px absolute overflow-auto rounded-md border bg-white p-2 shadow-lg">
                {variables.map((item, index) => (
                  <div
                    key={index}
                    className={`max-h-300px flex cursor-pointer items-center overflow-auto rounded-sm px-4 py-2 ${
                      selectedIndex === index ? 'bg-primary' : 'bg-white'
                    } ${selectedIndex === index ? 'text-white' : 'text-myGray-600'}`}
                    onClick={() => {
                      setHighlightedIndex(index);
                      selectOptionAndCleanUp(item);
                    }}
                    onMouseEnter={() => {
                      setHighlightedIndex(index);
                    }}
                  >
                    <FunctionOutlined />
                    {/* <Box ml={2} fontSize={'sm'} whiteSpace={'nowrap'}>
                      {item.key}
                      {item.key !== item.label && `(${t(item.label as any)})`}
                    </Box> */}
                  </div>
                ))}
              </div>,
              anchorElementRef.current,
            )
          : null;
      }}
    />
  );
}
